<template>
  <div>
    <MainContent title="职务管理">
      <template #search-bar>
        <SearchBar inline>
          <template #normal>
            <el-form-item>
              <el-input v-model="params.name" placeholder="职务名称" clearable>
              </el-input>
            </el-form-item>
          </template>
          <template #toolbar>
            <el-form-item>
              <el-button type="primary" @click="getPageList">查询</el-button>

              <el-button type="primary" icon="Plus" @click="addPosition" v-has="['1020']">新增</el-button>
            </el-form-item>
            <el-form-item>

              <!-- TODO 加权限 -->
              <el-button type="primary" @click="showExportData = true">导出</el-button>
            </el-form-item>

          </template>
        </SearchBar>
      </template>

      <el-table :data="state.tableData" row-key="id" stripe default-expand-all v-loading="state.isLoading">
        <!-- :filters="filterna" -->
        <!-- :filter-method="filterName" -->
        <el-table-column prop="name" label="职务名称" min-width="120" />
        <el-table-column prop="empCount" label="职务人员" min-width="120" />
        <el-table-column prop="description" label="职务描述" show-overflow-tooltip width="180" />
        <el-table-column prop="updateTime" label="更新时间" min-width="160">
          <template #default="scope">
            {{ new Date(scope.row.updateTime).format("yyyy-MM-dd hh:mm") }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button type="text" size="small" @click="editPositionForm(scope.row.id)" v-has="['1021']">编辑</el-button>
            <el-button type="text" size="small" v-has="['1022']" @click="delPosition(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination v-model:currentPage="params.current" v-model:page-size="params.size" :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper" :total="state.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </MainContent>
    <el-dialog class="dialog-form" v-model="dialogFormVisible" :title="title" width="50%" :close-on-click-modal="false"
      :before-close="resetForm">
      <el-form :model="form" ref="PositionForm" :rules="rules" label-width="80px">
        <el-form-item label="职务名称" prop="name">
          <el-input v-model="form.name" autocomplete="off" placeholder="职务名称" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="职务描述">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述信息" autocomplete="off" maxlength="100"
            show-word-limit />
        </el-form-item>
      </el-form>
      <div>
        <el-tabs v-model="activeName" class="tabmenu" style="">
          <el-tab-pane v-for="(item, index) in serviceList" :key="index" :label="nameFilter(item.serviceType)"
            :name="item.serviceType">
            <div v-for="(ite, idx) in appList" :key="ite.code">
              <el-cascader-panel v-if="item.serviceType == ite.code" v-model="permissionIdsAll[ite.code]"
                :options="item.permissionLayer" :props="props" />
            </div>
            <!-- <el-cascader-panel
              v-if="item.serviceType == 'MERCHANT'"
              v-model="merchantIds"
              :options="item.permissionLayer"
              :props="props"
            />
            <el-cascader-panel
              v-if="item.serviceType == 'ACTIVITY'"
              v-model="activityIds"
              :options="item.permissionLayer"
              :props="props"
            />
            <el-cascader-panel
              v-if="item.serviceType == 'FLOW'"
              v-model="flowIds"
              :options="item.permissionLayer"
              :props="props"
            />
            <el-cascader-panel
              v-if="item.serviceType == 'MALL'"
              v-model="mallIds"
              :options="item.permissionLayer"
              :props="props"
            />
            <el-cascader-panel
              v-if="item.serviceType == 'MATERIAL'"
              v-model="materialIds"
              :options="item.permissionLayer"
              :props="props"
            />
            <el-cascader-panel
              v-if="item.serviceType == 'MARKETING'"
              v-model="marketingIds"
              :options="item.permissionLayer"
              :props="props"
            />
            <el-cascader-panel
              v-if="item.serviceType == 'AD'"
              v-model="ADIds"
              :options="item.permissionLayer"
              :props="props"
            /> -->
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm()">取消</el-button>
          <el-button type="primary" @click="submitForm(PositionForm, edit)">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <exportData v-model:show-dialog="showExportData" :search-data="params" title="职务管理" export-type="roleExport">
    </exportData>
  </div>
</template>
<script lang="ts">
export default {
  name: 'OrganizationPosition'
}
</script>
<script lang="ts" setup>
import exportData from "@/components/exportData/exportData.vue";
import { reactive, onMounted } from "vue";
import {
  pageList,
  addNew,
  update,
  detail,
  del,
  normalTree,
  queryAppList
} from "@/api/orgPosition";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { positionReq, service } from "@/api/modules/orgPosition";
import { debounceUtils } from "@/utils/index.js";
// filterTemplate,
const router = useRouter();
const props = {
  multiple: true,
  label: "name",
  value: "id",
  expandTrigger: "hover",
};
const showExportData = ref(false)
const state = reactive({
  id: "",
  isLoading: false,
  total: 0,
  tableData: [] as Array<positionReq>,
});
const params = ref({
  name: "",
  size: 10,
  current: 1,
});
const activeName = ref("MERCHANT");
let serviceList = ref([] as Array<service>);
let form = ref({
  id: "",
  name: "",
  //描述
  description: "",
  // 应用权限
  permissionIds: [] as Array<any>,
});
// const merchantIds = ref([] as Array<any>);
// const activityIds = ref([] as Array<any>);
// const mallIds = ref([] as Array<any>);
// const flowIds = ref([] as Array<any>);
// const materialIds = ref([] as Array<any>);
// const ADIds = ref([] as Array<any>);
// const marketingIds = ref([] as Array<any>);
const permissionIdsAll = ref({});

const PositionForm = ref<FormInstance>();
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  params.value.size = val;
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  params.value.current = val;
};
let edit = ref(false);

const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入职务名称",
      trigger: "blur",
    },
  ],
});
const dialogFormVisible = ref(false);

let title = ref("新增职务");
const appList = ref([] as Array<any>);
const addPosition = () => {
  title.value = "新建职务";
  edit.value = false;
  resetForm();
  activeName.value = "MERCHANT";
  dialogFormVisible.value = true;
};
const editPositionForm = async (id: string | number): Promise<void> => {
  const rs = await detail({ id: id });
  if (rs.code == 200) {
    form.value.id = rs.payload.id;
    form.value.name = rs.payload.name;
    form.value.description = rs.payload.description;
    // merchantIds.value = rs.payload.permissionIds;
    // activityIds.value = rs.payload.permissionIds;
    // mallIds.value = rs.payload.permissionIds;
    // flowIds.value = rs.payload.permissionIds;
    // materialIds.value = rs.payload.permissionIds;
    // ADIds.value = rs.payload.permissionIds;
    // marketingIds.value = rs.payload.permissionIds;
    rs.payload.permissionResponses.forEach((ele: any) => {
      appList.value.forEach(i => {
        if (ele.serviceType == i.code) {
          permissionIdsAll.value[i.code] = ele.permissionIds;
        }
      })
      // if (ele.serviceType == "MERCHANT") {
      //   merchantIds.value = ele.permissionIds;
      // } else if (ele.serviceType == "ACTIVITY") {
      //   activityIds.value = ele.permissionIds;
      // } else if (ele.serviceType == "FLOW") {
      //   flowIds.value = ele.permissionIds;
      // } else if (ele.serviceType == "MALL") {
      //   mallIds.value = ele.permissionIds;
      // } else if (ele.serviceType == "MATERIAL") {
      //   materialIds.value = ele.permissionIds;
      // } else if (ele.serviceType == "MARKETING") {
      //   marketingIds.value = ele.permissionIds;
      // } else if (ele.serviceType == "AD") {
      //   ADIds.value = ele.permissionIds;
      // }
    });
    title.value = "编辑职务";
    edit.value = true;
    dialogFormVisible.value = true;
  }
};
const getAppPageList = async (): Promise<void> => {
  const rs = await queryAppList({
    simple: true,
    includeMerchant: true,
  });
  if (rs.code == 200) {
    appList.value = rs.payload;
  }
};
const handleCheckAllChange = (val: boolean) => { };
const submitForm = (formEl: FormInstance | undefined, edit: any) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      // const permit = [
      //   ...merchantIds.value,
      //   ...activityIds.value,
      //   ...mallIds.value,
      //   ...flowIds.value,
      //   ...materialIds.value,
      //   ...ADIds.value,
      //   ...marketingIds.value,
      // ];
      let permit: Array = []
      appList.value.forEach(i => {
        if (permissionIdsAll.value[i.code]) {
          permit.push(...permissionIdsAll.value[i.code])
        }
      })
      const temp = permit.flat(6);
      console.log(temp);
      form.value.permissionIds = Array.from(new Set(temp));
      console.log(Array.from(new Set(temp)));
      console.log(form.value.permissionIds);
      let rs;
      if (edit) {
        rs = await update(form.value);
      } else {
        rs = await addNew(form.value);
      }
      if (rs.code == 200) {
        resetForm();
        getPageList();
      }
    } else {
      console.log("报错啦！请重新使一下", fields);
    }
  });
};
const resetForm = () => {
  form.value = {
    id: "",
    name: "",
    //描述
    description: "",
    // 超管账号
    permissionIds: [] as Array<any>,
  };
  // merchantIds.value = [];
  // activityIds.value = [];
  // mallIds.value = [];
  // flowIds.value = [];
  // materialIds.value = [];
  // ADIds.value = [];
  // marketingIds.value = [];
  permissionIdsAll.value = {}
  PositionForm.value?.resetFields();
  dialogFormVisible.value = false;
};
const delPosition = async (row: any) => {
  ElMessageBox.confirm("确定删除吗？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const rs = await del({
        id: row.id,
        name: row.name
      });
      if (rs.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getPageList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消操作",
      });
    });
};
const getPageList = debounceUtils(async (): Promise<void> => {
  state.isLoading = true;
  const rs: any = await pageList(params.value);
  if (rs.code == 200) {
    state.total = rs.page.totalResult;
    state.tableData = rs.payload;
  }
  state.isLoading = false;
}, 500);
const nameFilter = (id: string) => {
  let name = "";
  // switch (id) {
  //   case "MERCHANT":
  //     name = "商户系统";
  //     break;
  //   case "ACTIVITY":
  //     name = "营销活动管理";
  //     break;
  //   case "FLOW":
  //     name = "营销自动化";
  //     break;
  //   case "MALL":
  //     name = "商城管理";
  //     break;
  //   case "MATERIAL":
  //     name = "内容管理";
  //     break;
  //   case "MARKETING":
  //     name = "员工营销管理";
  //     break;
  //   case "AD":
  //     name = "智能广告";
  //     break;
  // }
  appList.value.forEach(i => {
    if (i.code == id) {
      name = i.name
    }
  })
  return name;
};
const getNormalTree = async (): Promise<void> => {
  const rs = await normalTree();
  if (rs.code == 200) {
    serviceList.value = rs.payload;
  }
};
watch(params.value, (val) => {
  getPageList();
});

const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  () => {
    getAppPageList();
    getPageList();
    getNormalTree();
  },
  {
    deep: true
  }
)

onMounted(() => {
  getAppPageList();
  getPageList();
  getNormalTree();
});
</script>
<style lang="scss" scoped>
//:deep(.el-form) {
//  text-align: left;
//  margin-top: 18px;
//}
:deep(.el-button--text) {
  margin: 0 !important;
}

:deep(.el-table) {
  margin: 0 auto;
}

.page {
  margin: 10px auto;
}

.dialog-form {
  :deep(.el-date-editor) {
    width: 100%;
  }
}

.tabmenu {
  display: block;
  width: 100%;
  height: 300px;
}

:deep(.el-tabs__content) {
  height: 250px;
}
</style>
